package com.rzico.sbl.ui

import android.graphics.Bitmap
import android.net.http.SslError
import android.webkit.*
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityWebBinding
import com.xinnuo.common.extend.*
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.theme.BuildConfig

class WebActivity : BaseActivity(R.layout.activity_web) {

    private val mBinding by lazy { ActivityWebBinding.bind(getRootView()) }

    override fun initData() {
        initTitle(title = intent.getExtra("title"))

        initWeb()

        mBinding
            .webContent
            .loadUrl(
                when (intent.getExtra("title")) {
                    "用户协议" -> "${BuildConfig.API_HOST}/policy/protocol.html"
                    "隐私政策" -> "${BuildConfig.API_HOST}/policy/index.html"
                    "第三方SDK目录" -> "${BuildConfig.API_HOST}/policy/sdk.html"
                    "华为" -> "${BuildConfig.API_HOST}/app/huawei_cn.html"
                    "小米" -> "${BuildConfig.API_HOST}/app/mi_cn.html"
                    "VIVO" -> "${BuildConfig.API_HOST}/app/vivo_cn.html"
                    "OPPO" -> "${BuildConfig.API_HOST}/app/oppo_cn.html"
                    "使用教程" -> "${BuildConfig.API_HOST}/app/course_cn.html"
                    else -> "https://www.baidu.com/"
                }
            )
    }

    @Suppress("DEPRECATION")
    private fun initWeb() {
        mBinding.webContent.apply {
            //支持javascript
            settings.javaScriptEnabled = true
            //设置可以支持缩放
            settings.setSupportZoom(true)
            //自适应屏幕
            settings.loadWithOverviewMode = true
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            isHorizontalScrollBarEnabled = false

            //设置出现缩放工具
            settings.builtInZoomControls = true
            settings.displayZoomControls = false

            //设置是否使用缓存
            settings.setAppCacheEnabled(true)
            settings.domStorageEnabled = true

            webChromeClient = WebChromeClient()
            webViewClient = object : WebViewClient() {

                /*
                 * 当加载的网页需要重定向的时候就会回调这个函数告知我们应用程序是否需要接管控制网页加载，
                 * 如果应用程序接管，并且return true意味着主程序接管网页加载，如果返回false让webview自己处理
                 */
                @Deprecated("Deprecated in Java")
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return when {
                        "tel:" in url -> makeCall(url.replace("tel:", ""))
                        url.startsWith("weixin://wap/pay?") -> browse(url)
                        url.startsWith("https://developer.huawei.com") -> browse(url)
                        url.startsWith("https://dev.mi.com") -> browse(url)
                        url.startsWith("https://dev.vivo.com") -> browse(url)
                        url.startsWith("https://open.oppomobile.com") -> browse(url)
                        url.startsWith("https://lbs.amap.com") -> browse(url)
                        url.startsWith("https://cloud.tencent.com") -> browse(url)
                        url.startsWith("https://developer.umeng.com") -> browse(url)
                        url.endsWith(".apk") -> browse(url)
                        else -> {
                            view.loadUrl(url)
                            true
                        }
                    }
                }

                /*
                 * 在开始加载网页时会回调
                 */
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    showLoading()
                }

                /*
                 * 在结束加载网页时会回调
                 */
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    dismissLoading()
                }

                /*
                 * 当网页加载资源过程中发现SSL错误会调用此方法。
                 * 我们应用程序必须做出响应，是取消请求handler.cancel(),
                 * 还是继续请求handler.proceed(),
                 * 内核的默认行为是handler.cancel()
                 */
                override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler?,
                    error: SslError?
                ) {
                    handler?.proceed() ?: super.onReceivedSslError(view, handler, error)
                }

            }
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.webContent.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.webContent.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.webContent.destroy()
    }

    override fun onBackPressed() {
        mBinding
            .webContent
            .canGoBack()
            .conditionElse(
                actionTrue = { mBinding.webContent.goBack() },
                actionFalse = { super.onBackPressed() }
            )
    }

}